package com.example.learnquartz.quartz;

import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @description:
 * @author: 47 on 2020/4/9 15:07
 */
public class MonitorCronJob implements Job {

    private final static Logger logger = LoggerFactory.getLogger(MonitorCronJob.class);

    public static final String JOB_NAME = "monitor_cron";
    public static final String GROUP_NAME = "monitor";
    public static final String CRON = "0 0/10 * * * ?";
    public static final String DESC = "监控cron更新";

    @Autowired
    private SchedulerManager schedulerManager;

    @Autowired
    private SchedulerJobs schedulerJobs;

    /*@Autowired
    private ContextRefresher contextRefresher;
*/
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //重新加载配置
        // contextRefresher.refresh();
        Set<JobKey> oldJobKeys = null;
        try {
            oldJobKeys = jobExecutionContext.getScheduler().getJobKeys(GroupMatcher.anyJobGroup());
        } catch (SchedulerException e) {
            logger.error("MonitorCronJob {}", e);
        }

        List<String> newJobKeys = new ArrayList<>();
        for (SchedulerJob job : schedulerJobs.getJobs()) {
            //过滤掉monitor_cron任务
            if (job.getName().equals(JOB_NAME)) {
                continue;
            }
            newJobKeys.add(job.getName());
            logger.info("job【{}】,cron【{}】", job.getName(), job.getCron());
            schedulerManager.activeJob(job);
        }
        if (oldJobKeys == null) {
            return;
        }
        //删除没有配置的任务
        List<JobKey> shouldDeleteJobKeys = oldJobKeys.stream()
                .filter(jobKey -> !JOB_NAME.equals(jobKey.getName()) && !newJobKeys.contains(jobKey.getName()))
                .collect(Collectors.toList());
        logger.info("delete jobs {}", shouldDeleteJobKeys);
        schedulerManager.deleteJobs(shouldDeleteJobKeys);
    }
}
